#!/usr/bin/env node

/**
 * 健康检查脚本
 * 用于Docker容器和负载均衡器的健康监控
 */

const http = require('http');
const process = require('process');

// 配置
const config = {
  host: 'localhost',
  port: process.env.PORT || 3000,
  path: '/health',
  timeout: 5000
};

/**
 * 执行健康检查
 */
function healthCheck() {
  return new Promise((resolve, reject) => {
    const req = http.request({
      hostname: config.host,
      port: config.port,
      path: config.path,
      method: 'GET',
      timeout: config.timeout
    }, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const response = JSON.parse(data);
          
          if (res.statusCode === 200 && (response.status === 'ok' || response.status === 'healthy')) {
            resolve({
              status: 'healthy',
              statusCode: res.statusCode,
              response
            });
          } else {
            reject(new Error(`Health check failed: ${res.statusCode} - ${data}`));
          }
        } catch (error) {
          reject(new Error(`Invalid JSON response: ${error.message}`));
        }
      });
    });
    
    req.on('error', (error) => {
      reject(new Error(`Health check request failed: ${error.message}`));
    });
    
    req.on('timeout', () => {
      req.destroy();
      reject(new Error(`Health check timeout after ${config.timeout}ms`));
    });
    
    req.end();
  });
}

/**
 * 主函数
 */
async function main() {
  try {
    console.log(`[${new Date().toISOString()}] Starting health check...`);
    
    const result = await healthCheck();
    
    console.log(`[${new Date().toISOString()}] Health check passed:`, {
      status: result.status,
      statusCode: result.statusCode,
      response: result.response
    });
    
    process.exit(0);
  } catch (error) {
    console.error(`[${new Date().toISOString()}] Health check failed:`, error.message);
    process.exit(1);
  }
}

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
  console.error(`[${new Date().toISOString()}] Uncaught exception:`, error.message);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error(`[${new Date().toISOString()}] Unhandled rejection:`, reason);
  process.exit(1);
});

// 执行健康检查
if (require.main === module) {
  main();
}

module.exports = { healthCheck };